<template>
  <XenPageLayout
    title="编辑访客信息"
    title-align="left"
    navbar-bg-color="#7881de"
    navbar-text-color="#ffffff"
    navbar-icon-color="#ffffff"
    contentStyle="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); padding: 0; height: 100vh; display: flex; flex-direction: column;"
  >
    <!-- 表单内容区域 -->
    <view class="form-container">
      <XenDynamicFormCard
        title="编辑访客信息"
        :subtitle="`访客ID: ${visitorId || 'V12345'}`"
        :sections="formSections"
        :modelValue="formData"
        :errors="formErrors"
        footerMode="edit"
        @update:modelValue="handleFormDataChange"
        @fieldBlur="handleFieldBlur"
        @pickerChange="handlePickerChange"
        @datetimeChange="handleDateTimeChange"
        @imageUpload="handleImageUpload"
        @imageSuccess="handleImageSuccess"
        @imageFail="handleImageFail"
        @imageDelete="handleImageDelete"
        @fileUpload="handleFileUpload"
        @fileSuccess="handleFileSuccess"
        @fileFail="handleFileFail"
        @fileDelete="handleFileDelete"
        @save="handleSave"
      />
    </view>
  </XenPageLayout>
</template>

<script setup lang="ts">
import { onMounted, ref } from "vue";
import XenPageLayout from "@/layouts/XenPageLayout.vue";
import XenDynamicFormCard from "@/components/XenDynamicFormCard.vue";
import { getFormSectionsByPageType } from "./form-config";
import { useVisitorInfo } from "./composables/useInfo";
// 导入统一事件系统
import { VisitorInfoEvents } from "@/utils/eventBus";

// 获取路由参数
const visitorId = ref<string>("");

// 获取编辑页面的表单分组
const formSections = getFormSectionsByPageType("edit");

// 使用访客信息 Composable
const {
  formData,
  formErrors,
  validateField,
  handlePickerChange,
  handleDateTimeChange,
  handleIdCardPhotoUpload,
  handleIdCardPhotoDelete,
  initializeOptions,
  loadVisitorDetail,
  saveVisitor,
  search,
} = useVisitorInfo();

// 表单数据变化处理
const handleFormDataChange = (newData: Record<string, any>) => {
  Object.assign(formData, newData);
};

// 字段失焦处理
const handleFieldBlur = (fieldKey: string) => {
  validateField(fieldKey);
};

// 图片上传处理
const handleImageUpload = async (field: any, event: any) => {
  // 检查是否为身份证上传
  if (field.fileConfig?.isIdCard) {
    if (field.fileConfig.idCardType === "front") {
      await handleIdCardPhotoUpload("idCardFrontPhoto", event);
    } else if (field.fileConfig.idCardType === "back") {
      await handleIdCardPhotoUpload("idCardBackPhoto", event);
    }
  } else {
    // 其他图片上传逻辑
    console.log("普通图片上传:", field.key, event);
  }
};

const handleImageSuccess = (_field: any, _event: any) => {
  // 图片上传成功处理
};

const handleImageFail = (_field: any, _event: any) => {
  // 图片上传失败处理
};

const handleImageDelete = (field: any, event: any) => {
  // 检查是否为身份证删除
  if (field.fileConfig?.isIdCard) {
    if (field.fileConfig.idCardType === "front") {
      handleIdCardPhotoDelete("idCardFrontPhoto");
    } else if (field.fileConfig.idCardType === "back") {
      handleIdCardPhotoDelete("idCardBackPhoto");
    }
  } else {
    // 其他图片删除逻辑
    console.log("普通图片删除:", field.key, event);
  }
};

// 文件上传处理
const handleFileUpload = async (_field: any, _event: any) => {
  // 文件上传逻辑
};

const handleFileSuccess = (_field: any, _event: any) => {
  // 文件上传成功处理
};

const handleFileFail = (_field: any, _event: any) => {
  // 文件上传失败处理
};

const handleFileDelete = (_field: any, _event: any) => {
  // 文件删除处理
};

// 保存表单
const handleSave = async () => {
  try {
    uni.showLoading({ title: "保存中..." });

    // 使用Composable中的保存方法
    const response = await saveVisitor();

    uni.hideLoading();

    if (response.success && response.data && response.data.ID) {
      // 重新调用search接口获取最新的完整列表数据
      try {
        const searchResponse = await search({});
        if (searchResponse && searchResponse.length > 0) {
          // 发送完整列表数据更新事件
          VisitorInfoEvents.emit("refresh", {
            id: response.data.ID,
            data: searchResponse,
            customAction: "edit",
          });
        }
      } catch (error) {
        // 如果获取失败，仍然发送简单的刷新事件作为备用方案
        VisitorInfoEvents.emit("refresh", {
          id: response.data.ID,
          customAction: "edit",
        });
      }

      uni.showToast({
        title: "保存成功",
        icon: "success",
        success: () => {
          // 保存成功后返回列表页面
          setTimeout(() => {
            uni.navigateBack();
          }, 1000);
        },
      });
    } else {
      // 校验失败或保存失败，显示具体错误信息
      const errorMessage =
        response.validation?.firstErrorMessage ||
        response.error ||
        "保存失败，请重试";
      uni.showToast({
        title: errorMessage,
        icon: "none",
      });
    }
  } catch (error) {
    uni.hideLoading();
    uni.showToast({
      title: "保存失败，请重试",
      icon: "error",
    });
  }
};

// 组件挂载时加载数据
onMounted(async () => {
  // 先加载选项数据
  await initializeOptions();

  // 获取路由参数中的访客ID
  const pages = getCurrentPages();
  const currentPage = pages[pages.length - 1];
  const options = (currentPage as any).options;

  if (options && options.id) {
    visitorId.value = options.id;
    const success = await loadVisitorDetail(options.id);
  }
});
</script>

<style lang="scss" scoped>
.form-container {
  flex: 1;
  padding: 16px;
  overflow-y: auto;
}
</style>
